<script setup lang="ts">
import { ref,watchEffect } from 'vue'
import {  UploadOutlined } from '@ant-design/icons-vue';
import type { UploadProps } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import { pictureUploadproxy, articleSave, userSiteArticleSetRelease } from "../api/article"

const props:any = defineProps({
    open: Boolean,
    info: Object
})
const emits = defineEmits(['changeModel'])
const open_model = ref<boolean>(props.open);
const detailsInfo:any = ref({})

watchEffect(() => {
  console.log(props.open, props.info)
  open_model.value = props.open
  detailsInfo.value = props.info
}) 
// 确定发布
const handleOk = (e: MouseEvent) => {
  console.log(e, fileList.value,  detailsInfo.value['images']);
  open_model.value = false;
  let html_content:any = '' // html内容
  const resultData = fileList.value?.reduce((acc:any, item1:any) => {
    let matchingItem:any = ''
    if(!Array.isArray(detailsInfo.value['images'])) {
       matchingItem = JSON.parse(detailsInfo.value['images']).find((item2:any) => item2.url.slice(item2.url.lastIndexOf('/') + 1) === item1.name);
    } else {
       matchingItem = detailsInfo.value['images'].find((item2:any) => item2.url.slice(item2.url.lastIndexOf('/') + 1) === item1.name);
    }
    if (matchingItem) {
      acc.push({  ...matchingItem,...item1 }); // 将合并后的对象添加到结果数组中
    }
    return acc;
  }, []); // 初始值为空数组
  // html内容
  if(resultData.length > 0) {
    resultData.forEach((element:any, index:any) => {
      if(index == 0) {
        html_content = detailsInfo.value.html_content.replace(element.key, `<img src="${element.url}" alt="">`);
      } else {
        html_content = html_content.replace(element.key, `<img src="${element.url}" alt="">`);
      }
    });
  } else {
    html_content = detailsInfo.value.html_content
  }
  if(detailsInfo.value['min_title'] && !Array.isArray(detailsInfo.value['min_title']))  {
    JSON.parse(detailsInfo.value['min_title']).forEach((element:any) => {
      html_content = html_content.replace(element.label,element.html);
    });
  }else  {
    detailsInfo.value['min_title'].forEach((element:any) => {
      html_content = html_content.replace(element.label,element.html);
    })
  }
  const cover_image = fileList.value?.find((item:any) => detailsInfo.value.cover.slice(detailsInfo.value.cover.lastIndexOf('/') + 1) === item.name); // 封面图
  let cover_images_map = JSON.stringify([
      {
          'src': cover_image ? cover_image.url : '',
          'origin_src': cover_image ? cover_image.url : ''
      }
  ])
  let objData: any = {
        'type': 'news',
        'title': detailsInfo.value.title,
        'content': html_content,
        'creative_method': 'bjh_pc_text',
        'vertical_cover': '',  // 垂直图片
        'abstract': '',  // 摘要
        'len': html_content.length,
        'activity_list': [
            {'id': 408, 'is_checked': 1},
            {'id': 'ttv', 'is_checked': 0},
            {'id': 'aigc_bjh_status', 'is_checked': 0}
        ],
        'source_reprinted_allow': 0,
        'abstract_from': 1,
        'isBeautify': false,
        'usingImgFilter': false,
        'cover_layout': 'one',
        'cover_images': JSON.stringify([
            {
                'src': cover_image ? cover_image.url : '',
                'cropData': {
                    'x': 0,
                    'y': 0,
                    'width': 300,
                    'height': 200
                },
                'machine_chooseimg': 0,
                'isLegal': 0
            }
        ]),
        '_cover_images_map': cover_images_map,
        'source': 'choose-remote',
        'cover_source': 'upload',
        'subtitle': '',
        'bjhtopic_id': '',
        'bjhtopic_info': '',
        'clue': '',
        'bjhmt': '',
        'order_id': '',
        'aigc_rebuild': '',
        'image_edit_point': JSON.stringify([
            {'img_type': "cover", 'img_num': {'template': 0, 'font': 0, 'filter': 0, 'paster': 0, 'cut': 0, 'any': 0}},
            {'img_type': "body", 'img_num': {'template': 0, 'font': 0, 'filter': 0, 'paster': 0, 'cut': 0, 'any': 0}}
        ])
    }
    const searchParams = new URLSearchParams();
    Object.keys(objData).forEach(key => {
      if (Array.isArray(objData[key])) {
        objData[key].forEach(value => {
          searchParams.append(key, value); // 对于数组，使用 append 来添加多个值
        });
      } else {
        searchParams.append(key, objData[key]); // 对于其他类型，直接添加值
      }
    });
    console.log('objData', objData, searchParams.toString(), html_content)
    articleSave(objData).then((response:any) => {
        const result = response.data
        console.log('result',result)
        onuserSiteArticleSetRelease()
    }).catch((err) => console.log(err));
};

// 设置文章已发布
const onuserSiteArticleSetRelease = () => {
  userSiteArticleSetRelease({articleId: detailsInfo.value['article_id']}).then((response:any) => {
    console.log('response',response)
    message.success(response.massage);
    emits('changeModel', {open_model: false})
    fileList.value = []
  }).catch(err => {console.log(err)})
}
// 上传图片
function getBase64(file: File) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}

const previewVisible = ref(false);
const previewImage = ref('');
const previewTitle = ref('');

const fileList = ref<UploadProps['fileList']>([]);

const handleCancel = () => {
  previewVisible.value = false;
  previewTitle.value = '';
};
const handlePreview = async (file: any) => {
  if (!file.url && !file.preview) {
    file.preview = (await getBase64(file.originFileObj)) as string;
  }
  previewImage.value = file.url || file.preview;
  previewVisible.value = true;
  previewTitle.value = file.name || file.url.substring(file.url.lastIndexOf('/') + 1);
};

//主要用图片上传前的限制操作（非必写）
const beforeUpload = (file:any) => {
  // const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
  // if (!isJpgOrPng) {
  //   message.error('只能上传JPG、PNG格式图片!');
  // }
  // const isLt2M = file.size / 1024 / 1024 < 2;
  // if (!isLt2M) {
  //   message.error('图片尺寸不能超过2MB!');
  // }
  // return isJpgOrPng && isLt2M;
  console.log('file:any',file)
  return true;
};
// 图片上传
const loading = ref(false);
const handleChange = (info:any) => {
  loading.value=true

  //info.filename的值与a-upload里的name对应，这样就可以多个位置都使用同一方法
  const FormDatas = new FormData();
  FormDatas.append("type", 'image');
  FormDatas.append("app_id", '1788758126357619');
  FormDatas.append("is_waterlog", '0');
  FormDatas.append("save_material", '1');
  FormDatas.append("is_events", '');
  FormDatas.append("article_type", 'news');
  FormDatas.append("media", info.file);
  console.log('info', info, info.file.name, fileList.value)

  //api.upload_uploadImages后端给的图片上传解析的接口方法
  pictureUploadproxy(FormDatas).then((response:any) => {
    const result = response.ret
    const img = new Image();
    img.src = result.https_url;
    img.onload = () => {
      // 图片加载完成后，获取宽高
      console.log('Width:', img.width, 'Height:', img.height);
      // 可以在这里做一些处理，比如验证图片尺寸等
    };
    let file:any = []
    file = fileList.value?.filter((item:any) => item.uid == info.file.uid)
    if(file.length > 0) {
      file[0].status = 'done'
      file[0].url = result.https_url
    }
    // let arr:any = fileList.value
    // fileList.value =[...arr, ...file]
    // fileList.value?.concat(file)
  //   const resultData = fileList.value?.reduce((acc:any, item1:any) => {
  //   const matchingItem = JSON.parse(detailsInfo.value['images']).find((item2:any) => item2.url.slice(item2.url.lastIndexOf('/') + 1) === item1.name);
  //   console.log('matchingItem',matchingItem)
  //   if (matchingItem) {
  //     acc.push({  ...matchingItem,...item1 }); // 将合并后的对象添加到结果数组中
  //   }
  //   return acc;
  // }, []);
    console.log('result',result,file, fileList.value)
    loading.value=false
  }).catch()
  //将后端返回的图片路径值赋给所在图片所绑定的值
//   formTableData.value[idCard] = data 
};
// 删除
const handleRemove =(info:any)=> {
    console.log('info', info)
    fileList.value = fileList.value?.filter(i => i.uid !== info.uid);
}
</script>
<template>
  <div class="UploadPhoto">
    <a-modal v-model:open="open_model" title="上传发布" @ok="handleOk">
      <div>
        <!-- list-type="picture-card" -->
        <a-upload
          name="file"
          v-model:file-list="fileList"
          :before-upload="beforeUpload" 
          :customRequest="handleChange"
          @remove="handleRemove"
          @preview="handlePreview"
        >
        <!-- v-if="fileList.length < 8" -->
          <!-- <div>
            <plus-outlined />
            <div style="margin-top: 8px">Upload</div>
          </div> -->
          <a-button>
            <upload-outlined></upload-outlined>
            上传
          </a-button>
        </a-upload>
      </div>
    </a-modal>
    <a-modal :open="previewVisible" :title="previewTitle" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<style scoped>
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>